package com.css.zfzx.sjcj.modules.hddcwyVolcanicSvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.excel.handler.ActiveFaultVerifyBaseHandler;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcVolcanicSvyPoint.repository.HddcVolcanicsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcVolcanicSvyPoint.repository.entity.HddcVolcanicsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSvyPoint.repository.HddcWyVolcanicsvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSvyPoint.repository.HddcWyVolcanicsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSvyPoint.repository.entity.HddcWyVolcanicsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSvyPoint.service.HddcWyVolcanicsvypointService;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSvyPoint.viewobjects.HddcWyVolcanicsvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSvyPoint.viewobjects.HddcWyVolcanicsvypointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zyb
 * @date 2020-12-02
 */
@Service
public class HddcWyVolcanicsvypointServiceImpl implements HddcWyVolcanicsvypointService {

    private final HddcWyVolcanicsvypointRepository hddcWyVolcanicsvypointRepository;
    private final HddcWyVolcanicsvypointNativeRepository hddcWyVolcanicsvypointNativeRepository;
    private final HddcVolcanicsvypointRepository hddcVolcanicsvypointRepository;
    private final ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler;

    @Autowired
    public HddcWyVolcanicsvypointServiceImpl(HddcWyVolcanicsvypointRepository hddcWyVolcanicsvypointRepository,
                                             HddcWyVolcanicsvypointNativeRepository hddcWyVolcanicsvypointNativeRepository,
                                             HddcVolcanicsvypointRepository hddcVolcanicsvypointRepository,
                                             ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler) {
        this.hddcWyVolcanicsvypointRepository = hddcWyVolcanicsvypointRepository;
        this.hddcWyVolcanicsvypointNativeRepository = hddcWyVolcanicsvypointNativeRepository;
        this.hddcVolcanicsvypointRepository = hddcVolcanicsvypointRepository;
        this.activeFaultVerifyBaseHandler = activeFaultVerifyBaseHandler;
    }

    @Override
    public JSONObject queryHddcWyVolcanicsvypoints(HddcWyVolcanicsvypointQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyVolcanicsvypointEntity> hddcWyVolcanicsvypointPage = this.hddcWyVolcanicsvypointNativeRepository.queryHddcWyVolcanicsvypoints(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyVolcanicsvypointPage);
        return jsonObject;
    }


    @Override
    public HddcWyVolcanicsvypointEntity getHddcWyVolcanicsvypoint(String uuid) {
        HddcWyVolcanicsvypointEntity hddcWyVolcanicsvypoint = this.hddcWyVolcanicsvypointRepository.findById(uuid).orElse(null);
         return hddcWyVolcanicsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyVolcanicsvypointEntity saveHddcWyVolcanicsvypoint(HddcWyVolcanicsvypointEntity hddcWyVolcanicsvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyVolcanicsvypoint.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyVolcanicsvypoint.getCreateUser())){
            hddcWyVolcanicsvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyVolcanicsvypoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyVolcanicsvypoint.setIsValid("1");

        HddcVolcanicsvypointEntity hddcVolcanicsvypointEntity=new HddcVolcanicsvypointEntity();
        BeanUtils.copyProperties(hddcWyVolcanicsvypoint,hddcVolcanicsvypointEntity);
        hddcVolcanicsvypointEntity.setExtends4(hddcWyVolcanicsvypoint.getTown());
        hddcVolcanicsvypointEntity.setExtends5(String.valueOf(hddcWyVolcanicsvypoint.getLon()));
        hddcVolcanicsvypointEntity.setExtends6(String.valueOf(hddcWyVolcanicsvypoint.getLat()));
        this.hddcVolcanicsvypointRepository.save(hddcVolcanicsvypointEntity);

        this.hddcWyVolcanicsvypointRepository.save(hddcWyVolcanicsvypoint);
        return hddcWyVolcanicsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyVolcanicsvypointEntity updateHddcWyVolcanicsvypoint(HddcWyVolcanicsvypointEntity hddcWyVolcanicsvypoint) {
        HddcWyVolcanicsvypointEntity entity = hddcWyVolcanicsvypointRepository.findById(hddcWyVolcanicsvypoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyVolcanicsvypoint);
        hddcWyVolcanicsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyVolcanicsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyVolcanicsvypointRepository.save(hddcWyVolcanicsvypoint);
        return hddcWyVolcanicsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyVolcanicsvypoints(List<String> ids) {
        List<HddcWyVolcanicsvypointEntity> hddcWyVolcanicsvypointList = this.hddcWyVolcanicsvypointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWyVolcanicsvypointList) && hddcWyVolcanicsvypointList.size() > 0) {
            for(HddcWyVolcanicsvypointEntity hddcWyVolcanicsvypoint : hddcWyVolcanicsvypointList) {
                this.hddcWyVolcanicsvypointRepository.delete(hddcWyVolcanicsvypoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyVolcanicsvypoint(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyVolcanicsvypointNativeRepository.queryHddcWyVolcanicsvypoint(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyVolcanicsvypointEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyVolcanicsvypointEntity> list = hddcWyVolcanicsvypointRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }

    /**
     * 文件导出
     * @param queryParams
     * @param response
     */
    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyVolcanicsvypointEntity> hddcWyVolcanicsvypointEntity = hddcWyVolcanicsvypointNativeRepository.exportVolcanicPoint(queryParams);
        List<HddcWyVolcanicsvypointVO> list=new ArrayList<>();
        for (HddcWyVolcanicsvypointEntity entity:hddcWyVolcanicsvypointEntity) {
            HddcWyVolcanicsvypointVO hddcWyVolcanicsvypointVO=new HddcWyVolcanicsvypointVO();
            BeanUtils.copyProperties(entity,hddcWyVolcanicsvypointVO);
            list.add(hddcWyVolcanicsvypointVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"火山调查观测点-点","火山调查观测点-点", HddcWyVolcanicsvypointVO.class,"火山调查观测点-点.xls",response);
    }

    /**
     *   文件导入
     */
    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(activeFaultVerifyBaseHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcWyVolcanicsvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyVolcanicsvypointVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcWyVolcanicsvypointVO hddcWyVolcanicsvypointVO : result.getFailList()) {
                    returnMsg.append("第").append(hddcWyVolcanicsvypointVO.getRowNum()).append("行").append(hddcWyVolcanicsvypointVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcWyVolcanicsvypointVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList( List<HddcWyVolcanicsvypointVO> list) {
        for (HddcWyVolcanicsvypointVO wyVolcanicsvypointVO : list) {
            HddcWyVolcanicsvypointEntity hddcWyVolcanicsvypointEntity = new HddcWyVolcanicsvypointEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(wyVolcanicsvypointVO, hddcWyVolcanicsvypointEntity);
            saveHddcWyVolcanicsvypoint(hddcWyVolcanicsvypointEntity);
        }
    }

    @Override
    public List<HddcWyVolcanicsvypointEntity> findAllByCreateUserAndIsValid(String userId, String isValid) {
        return hddcWyVolcanicsvypointRepository.findAllByCreateUserAndIsValid(userId, isValid);
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyVolcanicsvypointEntity> hddcA1InvrgnhasmaterialtableList =
                this.hddcWyVolcanicsvypointRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyVolcanicsvypointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid(PlatformConstants.N);
                this.hddcWyVolcanicsvypointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyVolcanicsvypointEntity> hddcA1InvrgnhasmaterialtableList
                = this.hddcWyVolcanicsvypointRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyVolcanicsvypointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid(PlatformConstants.N);
                this.hddcWyVolcanicsvypointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }

}
